import { createRouter, createWebHashHistory } from 'vue-router';
import { useUserStore } from '@/store/userStore';
import PrivateRoutes from './private';
import PublicRoutes from './public';

const whiteList = ['Login', 'Register', 'Forget', 'Reset'];

export const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL),
  scrollBehavior(to) {
    if (to.hash) return { el: to.hash, behavior: 'smooth', top: 60 };

    return { top: 0 };
  },
  routes: [
    {
      path: '/',
      redirect: '/auth/login'
    },
    {
      path: '/:pathMatch(.*)*',
      component: () => import('@/views/pages/NotFound.vue')
    },
    PrivateRoutes,
    PublicRoutes
  ]
});

// 路由守卫，检查登录状态
router.beforeEach(async (to) => {
  const routeName = String(to.name);
  
  // 如果是白名单路由，直接放行
  if (whiteList.includes(routeName)) {
    return true;
  }
  
  // 检查用户是否已登录
  const userStore = useUserStore();
  const hasToken = userStore.getAccessToken;
  const hasUsername = userStore.getUsername;
  
  console.log('访问路由:', routeName, '路径:', to.path, 'token:', hasToken, 'username:', hasUsername);
  
  // 如果token或username为空，尝试从sessionStorage恢复
  if ((!hasToken || !hasUsername) && typeof window !== 'undefined') {
    try {
      const vuetifyStorage = sessionStorage.getItem('vuetify') || sessionStorage.getItem('vma');
      if (vuetifyStorage) {
        const storageData = JSON.parse(vuetifyStorage);
        if (storageData.token && storageData.username) {
          // 恢复用户状态
          userStore.setToken(storageData.token);
          userStore.setUsername(storageData.username);
          if (storageData.name) userStore.setUserInfo(storageData);
          console.log('从sessionStorage恢复用户状态成功');
          return true;
        }
      }
    } catch (error) {
      console.warn('恢复用户状态失败:', error);
    }
  }
  
  if (hasToken && hasUsername) {
    // 已登录，允许访问
    return true;
  } else {
    // 未登录，重定向到登录页
    console.log('用户未登录，重定向到登录页');
    return { name: 'Login' };
  }
});
